package com.liu.webstore.interceptor;

import com.liu.webstore.annotation.LoginRequired;
import com.liu.webstore.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author LiuYumei
 * @Date 2022/7/23 23:16
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断拦截的类型是否为一个方法
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 判断方法是否存在LoginRequired注解
            if (method.isAnnotationPresent(LoginRequired.class)) {
                LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
                // 如果方法中存在LoginRequired注解 且 权限中用户信息为空，则响应重定向到登录页面
                if (null != loginRequired && null == hostHolder.getUser()) {
                    response.sendRedirect(request.getContextPath() + "/login");
                    return false;
                }
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
